package com.chehejia.devmng.platform.controller;



import com.chehejia.common.model.StatusCode;
import com.chehejia.devmng.platform.base.model.Response;
import com.chehejia.devmng.platform.manager.AllotLongExcelManager;
import com.chehejia.devmng.platform.manager.LaPlanManager;
import com.chehejia.devmng.platform.model.allot.QueryLongPlanVo;
import com.chehejia.devmng.platform.util.EmptyUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.OffsetDateTime;

/**
 长线调配
 */
@Controller
@RequestMapping("allotLong")
public class AllotLongCtl  {

    @Autowired
    private LaPlanManager laPlanManager;

    @Autowired
    private AllotLongExcelManager allotLongExcelManager;

    /**
     * 跳转到短线调拨页面
     *
     * @return
     */
    @RequestMapping("/toLongAllotListPage")
    public String toLongAllotListPage() {
        return "allot/allotlong";
    }

    @RequestMapping(value = "/queryList",method =RequestMethod.POST )
    @ResponseBody
    public Response queryListByParam(@RequestBody QueryLongPlanVo vo){
       try {
           if (EmptyUtil.isEmpty(vo)){
               return Response.fail(StatusCode.INVALID_PARAMS_CONVERSION.code(),"查询长线参数不能为空！");
           }
           if (EmptyUtil.isEmpty(vo.getYear())){
               return Response.fail(StatusCode.INVALID_PARAMS_CONVERSION.code(),"查询长线【年度】不能为空！");
           }
           if (EmptyUtil.isEmpty(vo.getSpuCode())){
               return Response.fail(StatusCode.INVALID_PARAMS_CONVERSION.code(),"查询长线【spu编码】不能为空！");
           }
           return  Response.success(laPlanManager.queryListByYearAndSpu(vo.getYear(),vo.getSpuCode()));
       }catch (RuntimeException e){
           return Response.fail(StatusCode.INVALID_PARAMS_CONVERSION.code(),e.getMessage());
       }
    }

    /**
     * 导出产单模板
     * @param response
     */
    @RequestMapping("/export-allotlong-template/{type}")
    public void exportAllotTemplate(@PathVariable("type") String type,  HttpServletResponse response){
        HSSFWorkbook excelTemplate = allotLongExcelManager.createExcelTemplate();
        try {
            String time = OffsetDateTime.now().toString();
            response.setHeader("content-Type", "application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("长线调配_产量" +time + "" + ".xls", "utf-8"));
            excelTemplate.write(response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                excelTemplate.close();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
            }
        }
    }
}
